<?php
/**
 * @author Mingming Tang iamalazyrat@gmail.com
 */

class Gallery_Controller extends Base_Controller {

  public $restful = true;

  public function get_index() {
    $page = Input::get('p', 1);
    $per_page = 40;
    $collections = Collection::all();
    $cid = Input::get('cid', false);
    $collection = Collection::with('groups')->find($cid);
    if (!$collection) return Response::error('404');
    $tag = Input::get('tag', false);
    $tag = Tag::with('imgs')->where('name', '=', $tag)->where('collection_id', '=', $cid)->first();
    if (!$tag) {
      $groups = $collection->groups;
      if (is_array($groups) and !empty($groups)) {
         $first = array_shift($groups);
         $tags = explode(',', $first->tags);
         $f_tag = array_shift($tags);
	 $tag = Tag::with('imgs')->where('name', '=', $f_tag)->where('collection_id', '=', $cid)->first();
      }
    }
    
    if (!$tag) {
      $imgs = Img::with('product')->where('collection_id', '=', $cid)->order_by('id', 'desc')->skip($per_page * ($page - 1))->take($per_page)->get();
      $cnt = Img::with('product')->where('collection_id', '=', $cid)->count();
      $url = url('gallery') . "?cid={$cid}";
    } else {
      $img_ids = array();
      foreach ($tag->imgs as $img) $img_ids[] = $img->id;
      if (count($img_ids) > 0) {
        $imgs = Img::with('product')->where_in('id', $img_ids)->where('collection_id', '=', $cid)->order_by('id', 'desc')->skip($per_page * ($page - 1))->take($per_page)->get();
	$cnt = Img::with('product')->where_in('id', $img_ids)->where('collection_id', '=', $cid)->count();
      } else {
        $imgs = array();
        $cnt = 0;
      }
      $url = url('gallery') . "?cid={$collection->id}&tag={$tag->name}";
    }
    $page = Pagination::page($page, $cnt, 40, $url);
    return View::make('gallery.index.main')->with('imgs', $imgs)->with('page', $page)->with('cid', $collection->id)->with('collections', $collections)->with('tag', $tag);
  }
  
}

